#!/bin/bash -eu

in_md5_block=false
current_block=""
current_block_name=""
md5_begin_tag="// md5begin"
md5_end_tag="// md5end"
comment_begin="//"

startswith() {
  str=$1
  pat="^$2"
  echo $str | grep -q "$pat"
}

while read line
do
  if startswith "$line" "$md5_begin_tag"
  then
    in_md5_block=true
    current_block_name=$(
      echo $line | tail -c +$(expr length "$md5_begin_tag" + 2)
    )
  elif startswith "$line" "$md5_end_tag"
  then
    in_md5_block=false
    md5hash=$(echo -n $current_block | md5sum | cut -d ' ' -f 1)
    echo "$current_block_name $md5hash"
    current_block=""
  elif startswith "$(echo $line | sed -e 's/^\s*//')" "$comment_begin"
  then
    continue
  elif $in_md5_block
  then
    current_block="${current_block}$(echo "$line" | sed -e 's/\s//g')"
  fi
done
